<?php

namespace api\modules\v1\forms\patient;

use Yii;
use yii\base\Model;
use common\models\member\Member;
use common\models\patient\User;
use common\models\base\PatientDiseases;
use common\models\patient\MedicalRecords;

/**
 * 病历
 *
 * Class MedicalForm
 * @package api\modules\v1\forms\patient
 */
class MedicalForm extends Model
{
    /**
     * 病历ID
     *
     * @var
     */
    public $id;

    /**
     * 项目ID
     *
     * @var
     */
    public $project_id;

    /**
     * 患者ID
     *
     * @var
     */
    public $patient_user_id = 0;

    /**
     * 患者诊疗号
     *
     * @var
     */
    public $patient_card_id = '';

    /**
     * 生病时间【格式：2020-01-01】
     *
     * @var
     */
    public $sick_time;

    /**
     * 主诉
     *
     * @var
     */
    public $main_desc = '';

    /**
     * 现病史
     *
     * @var
     */
    public $now_medical_history = '';

    /**
     * 过敏史
     *
     * @var
     */
    public $allergy_history = '';

    /**
     * 既往史
     *
     * @var
     */
    public $jw_history = '';

    /**
     * 个人史
     *
     * @var
     */
    public $person_history = '';

    /**
     * 家族史
     *
     * @var
     */
    public $family_history = '';

    /**
     * 体格检查
     *
     * @var
     */
    public $physique_history = '';

    /**
     * 诊断
     *
     * @var
     */
    public $diagnose = '';

    /**
     * 辅助检查结果
     *
     * @var
     */
    public $auxiliary_result = '';

    /**
     * 治疗意见
     *
     * @var
     */
    public $clinic_opinion = '';

    /**
     * 病种ID
     *
     * @var
     */
    public $patient_diseases_id = 0;

    /**
     * 病种名
     *
     * @var
     */
    public $diseases_name = '';

    /**
     * 内容
     *
     * @var
     */
    public $desc = '';

    /**
     * 病历信息
     *
     * @var
     */
    protected $medicalInfo;

    /**
     * 患者信息
     *
     * @var
     */
    protected $patientInfo;

    /**
     * 病种信息
     *
     * @var
     */
    protected $patientDiseasesInfo;


    public function rules()
    {
        return [
            // 参数验证
            [['project_id', 'patient_user_id', 'desc'], 'required', 'message' => '{attribute}不能为空', 'on' => ['create-auxiliary']],
            [['project_id', 'patient_user_id'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit']],
            [['project_id', 'patient_card_id'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit_out']],

//            [['id'], 'checkId', 'skipOnEmpty' => false, 'on' => ['edit']],
            [['project_id'], 'checkProjectId', 'skipOnEmpty' => false, 'on' => ['create-auxiliary', 'edit', 'edit_out']],
            [['patient_user_id'], 'checkPatientUserId', 'skipOnEmpty' => false, 'on' => ['create-auxiliary', 'edit']],
            [['patient_card_id'], 'checkPatientCardId', 'skipOnEmpty' => false, 'on' => ['edit_out']],
            [['sick_time'], 'checkSickTime', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['main_desc'], 'checkMainDesc', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['now_medical_history'], 'checkNowMedicalHistory', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['allergy_history'], 'checkAllergyHistory', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['jw_history'], 'checkJwHistory', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['person_history'], 'checkPersonHistory', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['family_history'], 'checkFamilyHistory', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['physique_history'], 'checkPhysiqueHistory', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['diagnose'], 'checkdiagnose', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['auxiliary_result'], 'checkAuxiliaryResult', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['clinic_opinion'], 'checkClinicOpinion', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['patient_diseases_id'], 'checkPatientDiseasesId', 'skipOnEmpty' => true, 'on' => ['edit', 'edit_out']],
            [['desc'], 'checkDesc', 'skipOnEmpty' => true, 'on' => ['create-auxiliary']],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();

        // 新增辅助内容
         $scenarios['create-auxiliary'] = ['project_id', 'patient_user_id', 'desc'];

        // 编辑
        $scenarios['edit'] = ['project_id', 'patient_user_id', 'sick_time', 'main_desc', 'now_medical_history', 'allergy_history', 'jw_history', 'person_history', 'family_history', 'physique_history', 'diagnose', 'auxiliary_result', 'clinic_opinion', 'patient_diseases_id'];

        // 编辑（对外访问）
        $scenarios['edit_out'] = ['project_id', 'patient_card_id', 'sick_time', 'main_desc', 'now_medical_history', 'allergy_history', 'jw_history', 'person_history', 'family_history', 'physique_history', 'diagnose', 'auxiliary_result', 'clinic_opinion', 'patient_diseases_id'];

        return $scenarios;
    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'id' => '病历ID',
            'project_id' => '项目ID',
            'patient_user_id' => '患者ID',
            'patient_card_id' => '患者诊疗号',
            'sick_time' => '生病时间',
            'main_desc' => '主诉',
            'now_medical_history' => '现病史',
            'allergy_history' => '过敏史',
            'jw_history' => '既往史',
            'person_history' => '个人史',
            'family_history' => '家族史',
            'physique_history' => '体格检查',
            'diagnose' => '诊断',
            'auxiliary_result' => '辅助检查结果',
            'clinic_opinion' => '治疗意见',
            'patient_diseases_id' => '诊断',
            'desc' => '内容',
        ];
    }

    /**
     * 检验病历ID
     *
     * @param $attribute
     * @return bool
     */
    /*public function checkId($attribute)
    {
        $medicalRecords = $this->getMedical();
        if (!$medicalRecords) {
            $this->addError($attribute, '参数错误[id_error]');
            return true;
        }

        if ($medicalRecords->patient_user_id != $this->patient_user_id || $medicalRecords->project_id != $this->project_id) {
            $this->addError($attribute, '参数错误[id_error]');
            return true;
        }
    }*/

    /**
     * 检验项目ID
     *
     * @param $attribute
     * @return bool
     */
    public function checkProjectId($attribute)
    {
        if ($this->getScenario() == 'edit_out') {
            $project = Yii::$app->services->project->findById($this->project_id);

            if (!$project) {
                $this->addError($attribute, '参数错误[project_id_error]');
                return true;
            }
        } else {
            if (Yii::$app->user->identity->member->is_super == Member::IS_SUPER_YES) {
                return true;
            }

            $attr = Yii::$app->services->attr->findInfo([
                'member_id' => Yii::$app->user->identity->member_id,
                'project_id' => $this->project_id,
            ]);

            if (!$attr) {
                $this->addError($attribute, '未绑定当前项目，无法操作');
                return true;
            }
        }
    }

    /**
     * 检验患者ID
     *
     * @param $attribute
     * @return bool
     */
    public function checkPatientUserId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $patient = $this->getPatient();
        if (!$patient) {
            $this->addError($attribute, '参数错误[id_error]');
            return true;
        }

        if ($patient->status == User::STATUS_DELETE) {
            $this->addError($attribute, '患者已删除，无法操作');
            return true;
        }
    }

    /**
     * 检验患者诊疗号
     *
     * @param $attribute
     * @return bool
     */
    public function checkPatientCardId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $patient = $this->getPatientByCradId();
        if (!$patient) {
            $this->addError($attribute, '参数错误[patient_card_id_error]');
            return true;
        }

        if ($patient->status == User::STATUS_DELETE) {
            $this->addError($attribute, '患者已删除，无法操作');
            return true;
        }
        
        $this->patient_user_id = $patient->id;
    }

    /**
     * 校验生病时间
     *
     * @param $attribute
     */
    public function checkSickTime($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $dateArr = explode('-', $this->sick_time);
        if(count($dateArr) != 3 || !checkdate($dateArr[1], $dateArr[2], $dateArr[0])) {
            $this->addError($attribute, '生病时间格式错误');
            return true;
        }
    }

    /**
     * 校验主诉
     *
     * @param $attribute
     */
    public function checkMainDesc($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->main_desc);
        if ($len > 200) {
            $this->addError($attribute, '主诉内容过长，最多200个字');
            return true;
        }
    }

    /**
     * 校验现病史
     *
     * @param $attribute
     */
    public function checkNowMedicalHistory($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->now_medical_history);
        if ($len > 200) {
            $this->addError($attribute, '现病史内容过长，最多200个字');
            return true;
        }
    }

    /**
     * 校验过敏史
     *
     * @param $attribute
     */
    public function checkAllergyHistory($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->allergy_history);
        if ($len > 200) {
            $this->addError($attribute, '过敏史内容过长，最多200个字');
            return true;
        }
    }

    /**
     * 校验既往史
     *
     * @param $attribute
     */
    public function checkJwHistory($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->jw_history);
        if ($len > 200) {
            $this->addError($attribute, '既往史内容过长，最多200个字');
            return true;
        }
    }

    /**
     * 校验个人史
     *
     * @param $attribute
     */
    public function checkPersonHistory($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->person_history);
        if ($len > 200) {
            $this->addError($attribute, '个人史内容过长，最多200个字');
            return true;
        }
    }

    /**
     * 校验家族史
     *
     * @param $attribute
     */
    public function checkFamilyHistory($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->family_history);
        if ($len > 200) {
            $this->addError($attribute, '家族史内容过长，最多200个字');
            return true;
        }
    }

    /**
     * 校验体格检查
     *
     * @param $attribute
     */
    public function checkPhysiqueHistory($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->physique_history);
        if ($len > 200) {
            $this->addError($attribute, '体格检查内容过长，最多200个字');
            return true;
        }
    }

    /**
     * 校验诊断
     *
     * @param $attribute
     */
    public function checkdiagnose($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->diagnose);
        if ($len > 200) {
            $this->addError($attribute, '诊断内容过长，最多200个字');
            return true;
        }
    }

    /**
     * 校验辅助检查结果
     *
     * @param $attribute
     */
    public function checkAuxiliaryResult($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->auxiliary_result);
        if ($len > 200) {
            $this->addError($attribute, '辅助检查结果内容过长，最多200个字');
            return true;
        }
    }

    /**
     * 校验治疗意见
     *
     * @param $attribute
     */
    public function checkClinicOpinion($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->clinic_opinion);
        if ($len > 200) {
            $this->addError($attribute, '治疗意见内容过长，最多200个字');
            return true;
        }
    }

    /**
     * 校验病种ID
     *
     * @param $attribute
     */
    public function checkPatientDiseasesId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if ($this->patient_diseases_id > 0) {
            $patientDiseases = $this->getPatientDiseases();
            if (!$patientDiseases) {
                $this->addError($attribute, '参数错误[patient_diseases_id_error]');
                return true;
            }

            if ($patientDiseases->status != PatientDiseases::STATUS_ENABLE) {
                $this->addError($attribute, '病种未启用，无法操作');
                return true;
            }
        }
    }

    /**
     * 校验内容
     *
     * @param $attribute
     */
    public function checkDesc($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->desc);
        if ($len > 200) {
            $this->addError($attribute, '内容过长，最多200个字');
            return true;
        }
    }

    /**
     * 获取病历信息
     *
     * @return MedicalRecords|null
     */
    public function getMedical()
    {
        if (is_null($this->medicalInfo)) {
            $this->medicalInfo = Yii::$app->services->patientMedicalRecords->findInfo([
                'project_id' => $this->project_id,
                'patient_user_id' => $this->patient_user_id,
            ]);
        }

        return $this->medicalInfo;
    }

    /**
     * 获取患者信息
     *
     * @return User|null
     */
    public function getPatient()
    {
        if (is_null($this->patientInfo)) {
            $this->patientInfo = Yii::$app->services->patientUser->findById($this->patient_user_id);
        }

        return $this->patientInfo;
    }

    /**
     * 根据诊疗号获取患者信息
     *
     * @return User|null
     */
    public function getPatientByCradId()
    {
        if (is_null($this->patientInfo)) {
            $this->patientInfo = $patientUser = Yii::$app->services->patientUser->findInfo([
                'patient_card_id' => $this->patient_card_id
            ]);
        }

        return $this->patientInfo;
    }

    /**
     * 获取病种信息
     *
     * @return PatientDiseases|null
     */
    public function getPatientDiseases()
    {
        if (is_null($this->patientDiseasesInfo)) {
            $this->patientDiseasesInfo = Yii::$app->services->patientDiseases->findById((int)$this->patient_diseases_id);
        }

        return $this->patientDiseasesInfo;
    }
}
